
import urlparse, urllib
from .dict import Dict

class URL(Dict):

    def __init__(self, url, scheme=None, host=None, path=None, params=None, 
                fragment=None, query=None, qargs={}):
        """create a URL object from the given url string"""
        # 1. parse the url string with urlparse
        if type(url) == URL:
            pr = urlparse.urlparse(str(url))
        else:
            pr = urlparse.urlparse(url)
        # 2. deal with parameters
        self.scheme     = scheme or pr.scheme
        self.host       = host or pr.netloc
        self.path       = path or pr.path
        self.params     = params or pr.params
        self.fragment   = fragment or pr.fragment
        # 3. deal with query arguments
        d = Dict(**urlparse.parse_qs(query or pr.query))
        for k in d:
            d[k] = d[k][-1]     # only keep the last instance of an argument
            if d[k] in [None, '']: _=d.pop('k')
        self.qargs = d
        for k in qargs.keys():
            if qargs[k] in ['', None]: 
                if k in self.qargs.keys():
                    _=self.qargs.pop(k)
            else:
                self.qargs[k] = qargs[k]

    def qstring(self):
        return urllib.urlencode(self.qargs)

    def __str__(self):
        pr = (self.scheme, self.host, self.path,
            self.params, self.qstring(), self.fragment )
        return urlparse.urlunparse(pr)